package com.haifeng.lyw.blerobot.custom;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.haifeng.lyw.blerobot.R;


/**
 * Created by lyw on 2017/8/18.
 */

public class RemoteSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private float scale = this.getResources().getDisplayMetrics().density;
    private Thread th;
    private SurfaceHolder sfh;
    private Canvas canvas;
    private Paint paint;
    private boolean flag;

    private int bigCircleX = 0;
    private int bigCircleY = 0;
    private int bigCircleR = 0;
    //摇杆的X,Y坐标以及摇杆的半径
    private float smallCircleX = 0;
    private float smallCircleY = 0;
    private int smallCircleR = 0;


    private Bitmap bitmap;
    private Bitmap upBmp;
    private Bitmap dowmBmp;
    private Bitmap leftBmp;
    private Bitmap rightBmp;
    private RemoteViewBg remoteViewBg;
    private RemoteViewBg mUpImg;
    private RemoteViewBg mDownImg;
    private RemoteViewBg mLeftImg;
    private RemoteViewBg mRightImg;

    public RemoteSurfaceView(Context context) {
        super(context);
        sfh = this.getHolder();
        sfh.addCallback(this);
        paint = new Paint();
        paint.setAntiAlias(true);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setZOrderOnTop(true);
        getHolder().setFormat(PixelFormat.TRANSPARENT);

    }

    public void surfaceCreated(SurfaceHolder holder) {
        int width = getWidth();
        int height = getHeight();
        smallCircleR = width / 10;

        smallCircleX = width / 2;
        smallCircleY = height / 2;


        bigCircleX = width / 2;
        bigCircleY = height / 2;
        bigCircleR = (int) (width / 2 - smallCircleR);

        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.fangxiang);
        remoteViewBg = new RemoteViewBg(bitmap);
        setArrows(0);

        th = new Thread(this);
        flag = true;
        th.start();


    }

    private void setArrows(int direction) {
        if (direction == 1) {
            upBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_up_press);
        } else {
            upBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_up);
        }
        mUpImg = new RemoteViewBg(upBmp);

        if (direction == 2) {
            dowmBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_down_press);
        } else {
            dowmBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_down);
        }
        mDownImg = new RemoteViewBg(dowmBmp);

        if (direction == 3) {
            leftBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_left_press);
        } else {
            leftBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_left);
        }
        mLeftImg = new RemoteViewBg(leftBmp);

        if (direction == 4) {
            rightBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_right_press);
        } else {
            rightBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.custom_right);
        }
        mRightImg = new RemoteViewBg(rightBmp);

    }

    /***
     * 得到两点之间的弧度
     */
    public float getRad(float px1, float py1, float px2, float py2) {
        float x = px2 - px1;

        float y = py1 - py2;
        //斜边的长
        float z = (float) Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        float cosAngle = x / z;
        float rad = (float) Math.acos(cosAngle);

        if (py2 < py1) {
            rad = -rad;
        }
        return rad;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
            // 在范围外触摸
            if (Math.sqrt(Math.pow((bigCircleX - (int) event.getX()), 2) + Math.pow((bigCircleY - (int) event.getY()), 2)) >= bigCircleR) {
                changeOutCirclePosition(event);

                double tempRad = getRad(bigCircleX, bigCircleY, event.getX(), event.getY());
                getXY(bigCircleX, bigCircleY, bigCircleR, tempRad);
            } else {//范围内触摸
                smallCircleX = (int) event.getX();
                smallCircleY = (int) event.getY();
            }
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            smallCircleX = bigCircleX;
            smallCircleY = bigCircleY;
            setArrows(0);
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    private void changeOutCirclePosition(MotionEvent e) {
        //第一步，确定有效的触摸点集
        float X = e.getX();
        float Y = e.getY();

        float aX = (X - bigCircleR);
        float aY = (Y - bigCircleR);
        float angle = (float) Math.atan2(Math.abs(aY), Math.abs((aX)));
        int direction = 0;//1、上；2下；3、左；4、右；
        if (aX > 0 && aY >= 0) {
//            360-0  第四象限
            if (angle <= 0.3827) {
                //右
                direction = 4;
            } else {
                //下
                direction = 2;
            }
        } else if (aX >= 0 && aY < 0) {
            //0-90 第一象限
            if (angle <= 0.3827) {
                //右
                direction = 4;
            } else {
                //上
                direction = 1;
            }
        } else if (aX < 0 && aY >= 0) {
            //180-270   第三象限
            if (angle <= 0.3827) {
                //左
                direction = 3;
            } else {
                //下
                direction = 2;
            }
        } else if (aX <= 0 && aY < 0) {
            //90-180   第二象限
            if (angle <= 0.3827) {
                //左
                direction = 3;
            } else {
                //上
                direction = 1;
            }
        }
        setArrows(direction);

    }


    public void getXY(float x, float y, float R, double rad) {
        //获取圆周运动的X坐标
        smallCircleX = (float) (R * Math.cos(rad)) + x;
        //获取圆周运动的Y坐标
        smallCircleY = (float) (R * Math.sin(rad)) + y;
    }

    public void draw() {
        try {
            canvas = sfh.lockCanvas();
            canvas.drawColor(getResources().getColor(R.color.white));

            paint.reset();
            paint.setAntiAlias(true);
            // 指定图片绘制区域(左上角的四分之一)
            Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            // 指定图片在屏幕上显示的区域
            Rect dst = new Rect(bigCircleX - bigCircleR, bigCircleY - bigCircleR, bigCircleX + bigCircleR, bigCircleY + bigCircleR);
            // 绘制图片
            remoteViewBg.draw(canvas, paint, src, dst);

            //左
            // 指定图片绘制区域(左上角的四分之一)
            Rect srcL = new Rect(0, 0, leftBmp.getWidth(), leftBmp.getHeight());
            // 指定图片在屏幕上显示的区域
            Rect dstL = new Rect(smallCircleR + 25, bigCircleR + smallCircleR - 40, smallCircleR + 70, smallCircleR + bigCircleR + 40);
            // 绘制图片
            mLeftImg.draw(canvas, paint, srcL, dstL);


            //上
            // 指定图片绘制区域(左上角的四分之一)
            Rect srcUp = new Rect(0, 0, upBmp.getWidth(), upBmp.getHeight());
            // 指定图片在屏幕上显示的区域
            Rect dstUp = new Rect(bigCircleR + smallCircleR - 40, smallCircleR + 25, smallCircleR + bigCircleR + 40, smallCircleR + 70);
            // 绘制图片
            mUpImg.draw(canvas, paint, srcUp, dstUp);


            //右
            // 指定图片绘制区域(左上角的四分之一)
            Rect srcR = new Rect(0, 0, rightBmp.getWidth(), rightBmp.getHeight());
            // 指定图片在屏幕上显示的区域
            Rect dstR = new Rect(smallCircleR + bigCircleR * 2 - 55, smallCircleR + bigCircleR - 40, smallCircleR + bigCircleR * 2 - 25, smallCircleR + bigCircleR + 40);
            // 绘制图片
            mRightImg.draw(canvas, paint, srcR, dstR);


            //下
            // 指定图片绘制区域(左上角的四分之一)
            Rect srcDown = new Rect(0, 0, dowmBmp.getWidth(), dowmBmp.getHeight());
            // 指定图片在屏幕上显示的区域
            Rect dstDown = new Rect(smallCircleR + bigCircleR - 40, smallCircleR + bigCircleR * 2 - 55, smallCircleR + bigCircleR + 40, smallCircleR + bigCircleR * 2 - 25);
            // 绘制图片
            mDownImg.draw(canvas, paint, srcDown, dstDown);

            paint.setColor(0x70ff0000);
            //绘制摇杆
            canvas.drawCircle(smallCircleX, smallCircleY, smallCircleR, paint);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            try {
                if (canvas != null)
                    sfh.unlockCanvasAndPost(canvas);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public void run() {

        while (flag) {
            draw();
            /*try {
                Thread.sleep(50);
            } catch (Exception ex) {
                ex.printStackTrace();
            }*/
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {


    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        flag = false;

    }
}
